package org.example;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用二维字符串数组存储数据
 */
public class ReadTableOne {
    public static void main(String[] args) {
        try {
            long startTime = System.currentTimeMillis();

            FileInputStream fis = new FileInputStream("src/main/resources/demo.docx");
            XWPFDocument document = new XWPFDocument(fis);
            
            // 获取文档中的第一个表格
            XWPFTable table = document.getTables().get(0);

            // 获取表格在元素中的索引
            int tableIndex = document.getBodyElements().indexOf(table);
            XWPFParagraph paragraph = (XWPFParagraph) document.getBodyElements().get(tableIndex - 1);
            System.out.println(paragraph.getText());

            List<List<String>> data = new ArrayList<>();

            // 表格行
            for (int rowIndex = 0; rowIndex < table.getNumberOfRows(); rowIndex++) {
                List<String> rowData = new ArrayList<>();
                // 获取行数据
                XWPFTableRow row = table.getRow(rowIndex);
                if (row == null) continue;

                List<XWPFTableCell> cells = row.getTableCells();
                for (int cellIndex = 0; cellIndex < cells.size(); cellIndex++) {
                    XWPFTableCell cell = cells.get(cellIndex);
                    CTTc tc = cell.getCTTc();

                    CTTcPr tcPr = tc.isSetTcPr() ? tc.getTcPr() : null;
                    STMerge vMerge = tcPr != null && tcPr.isSetVMerge() ? tcPr.getVMerge().xgetVal() : null;

                    // 该单元格参与合并
                    if (vMerge != null && "continue".equals(vMerge.getStringValue())) {
                        rowData.add(data.get(data.size() - 1).get(cellIndex));
                    } else {
                        rowData.add(cell.getText());
                    }
                }
                data.add(rowData);
            }
            for (List<String> row : data) {
                System.out.println(row);
            }

            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            System.out.println("程序运行时间为：" + totalTime);
        } catch (IOException e) {
            e.fillInStackTrace();
        }
    }
}
